//============================================================================
// Name        : main.cpp
// Author      : tanjiazhang
// Version     :
// Copyright   : free
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include "common/thread.h"
#include "network/epoll.h"
#include "network/std_network.h"
#include "stdio.h"

using namespace std;
using namespace light;

void* test()
{
	cout<<"Hello Thread test!"<<endl;
}
void* runServer()
{
	try
	{
		network::Epoll e;
		e.bind("127.0.0.1", 6060);
		e.start();
		cout<<"start"<<endl;
	}
	catch(network::NetworkException e)
	{
		cerr<<e.what()<<endl;
	}
}

void* runClient();

int main() {

	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

	Thread t(runServer);
	t.start();

	Thread::sleep(2000);
	runClient();
	t.join();
	return 0;
}

void* runClient()
{
	sockaddr_in server;
	memset(&server, 0, sizeof(server));
	server.sin_family = AF_INET;
	server.sin_port = htons(6060);
	server.sin_addr.s_addr = inet_addr("127.0.0.1");

//	int servFD = socket(PF_INET, SOCK_STREAM, 0);
//	if(bind(servFD, (sockaddr*)&server, sizeof(server))!=0)
//		perror("bind");
//	int client = listen(servFD, 200);
//	if(client<=0)
//		perror("listen");
//	sockaddr_in cs;
//	memset(&cs, 0, sizeof(cs));
//	cs.sin_family = AF_INET;
//	cs.sin_port = htons(6060);
//	cs.sin_addr.s_addr = inet_addr("127.0.0.1");
//	socklen_t css = sizeof(cs);
//	client = accept(servFD, (sockaddr*)&cs, &css);
//	cout<<"in: "<<client<<endl;

	int sockFD = socket(PF_INET, SOCK_STREAM, 0);

	int info = connect(sockFD, (sockaddr*)&server, sizeof(server));
	if(info!=0)
	{
		perror("connect");
		return 0;
	}

	char buf[20] = "Hello";
	info = send(sockFD, buf, sizeof(buf), 0);
	if(info<0)
	{
		perror("send");
		return 0;
	}

	cout<<"fin"<<endl;
}
